import deviceApi from '../../../api/deviceInfo';
import storage from '../../../utils/storage';
import {toast} from "../../../utils/util";
Page({
  data: {
    visible: false,
    style: 'border: 1rpx solid #008b28;border-radius: 12rpx;padding: 20rpx',
    styleCell: 'border-radius: 12rpx;padding: 20rpx;margin-bottom: 24rpx;background:#fff',
    pageSize: 10,
    pageNum: 1,
    status: 'more',
    list: [],
    groupName: '',
    id: '',
    title: '添加分组',
    userId: storage.get('userInfo').id
  },
  onLoad: function (options) {
    this.init();
  },
  init () {
    let params = {
      pageSize: this.data.pageSize,
      pageNum: this.data.pageNum
    }
    deviceApi.getDeviceGroupList(params).then(res => {
      this.data.list = this.data.list.concat(res.rows)
      this.data.pageNum++
      this.setData({
        list: this.data.list,
        pageNum: this.data.pageNum
      })
      if(res.rows.length < this.data.pageSize){
        this.setData({
          status: 'noMore',
        })
      }
    })
  },
  addGroup () {
    this.setData({
      visible: true,
      groupName: null,
      title: '添加分组',
      id: null
    })
  },
  editGroup(e) {
    let { name, id } = e.currentTarget.dataset;
    this.setData({
      visible: true,
      groupName: name,
      id: id,
      title: '编辑分组'
    })
  },
  onVisibleChange(e) {
    this.setData({
      visible: e.detail.visible,
    });
  },
  changeTap (e) {
    this.setData({
      groupName: e.detail.value
    })
  },
  async submitFrom() {
    if(!this.data.groupName) {
      return toast('设备名称不能为空')
    }
    this.data.id ? await deviceApi.editDeviceGroup({name: this.data.groupName,id: this.data.id}) : await deviceApi.addDeviceGroup({name: this.data.groupName});
    this.reset();
    this.init();
    toast('操作成功');
    this.setData({
      visible: false,
    })
  },
  reset () {
    this.setData({
      pageNum: 1,
      list: []
    })
  },
  onChoice (e) {
    let { id } = e.currentTarget.dataset;
    deviceApi.deleteDevice(id).then(res => {
      this.reset();
      this.init();
      toast('操作成功');
    })
  },
  
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if(this.data.status = 'noMore') {
      return
    }
    this.init();
  },
});